#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIView.h>
#import <UIKit/UIView-Geometry.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UITransitionView.h>
#import <UIKit/UIPreferencesTable.h>
#import <UIKit/UIPreferencesTextTableCell.h>
#import <UIKit/UIPreferencesControlTableCell.h>
#import <UIKit/UIPreferencesTableCell.h>
#import <UIKit/UISegmentedControl.h>
#import <UIKit/UISwitchControl.h>
#import <UIKit/UITextLabel.h>
#import <UIKit/UIAlertSheet.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UIAlertSheet.h>
#import <UIKit/UIAnimator.h>
#import <UIKit/UIAnimation.h>
#import <UIKit/UITransformAnimation.h>
#import <UIKit/UIViewHeartbeat.h>
#import <CoreGraphics/CoreGraphics.h>
#import "LanguageChooser.h"

@implementation LanguageChooser

- (void) applicationDidFinishLaunching: (id) unused
{
    struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

    UIWindow *window = [[UIWindow alloc] initWithContentRect: rect];
   
    _path=[[NSBundle mainBundle]
			      objectForInfoDictionaryKey:@"Preference Path"];
    _gpref=[[NSBundle mainBundle]
			      objectForInfoDictionaryKey:@"Global Preference Path"];
    [window orderFront: self];
    [window makeKey: self];
    [window _setHidden: NO];

    UINavigationBar *nav = [[UINavigationBar alloc] initWithFrame: rect];
    UINavigationItem *tempItem = [[UINavigationItem alloc]
    	     initWithTitle: @"Language Chooser"];
    [nav pushNavigationItem:tempItem];
    [nav setBarStyle: 0];

    UIView *mainView = [[UIView alloc] initWithFrame: rect];
    [mainView addSubview: nav]; 

    preferencesTable = [[UIPreferencesTable alloc] initWithFrame:
        CGRectMake(0.0f, 48.0f, rect.size.width, rect.size.height)];	
    
    [preferencesTable setDataSource:self];
    [preferencesTable setDelegate:self];
    [mainView addSubview:preferencesTable];

    currentLanguageCell = [[UIPreferencesTableCell alloc] initWithFrame:
        CGRectMake(0.0f, 0.0f, rect.size.width, 48.0f)];
    //NSString *str = [NSString stringWithFormat:@"%d",[defaults textSize]];
    NSString *currLang;
    currLang = NSLocalizedString (@"English", @"Comment");
    [currentLanguageCell setValue:currLang];
    [currentLanguageCell setTitle:@"Language"];
    [currentLanguageCell setEnabled: NO];

    langArray = [[NSMutableArray alloc] init];
    langDict = [[NSMutableDictionary alloc] init];    
    [self getSelection];

    [preferencesTable reloadData];
    [window setContentView: mainView]; 
}

- (void)getSelection {
    struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *tempArray = [[NSArray alloc] initWithArray:[fileManager directoryContentsAtPath:[_path stringByAppendingString:@"preferences/"]]];

    if ([fileManager fileExistsAtPath: _path] == NO) {
        return;
    }

    NSString *file;
    UIPreferencesTableCell *languageSwitcher;
    NSEnumerator *dirEnum = [tempArray objectEnumerator];
    while (file = [dirEnum nextObject]) {
        if ([file characterAtIndex:0] != (unichar)'.')
        {  // Skip invisibles, like .DS_Store
            NSString *lang = [[NSBundle mainBundle]
			      objectForInfoDictionaryKey:file];
            languageSwitcher = [[UIPreferencesTableCell alloc] initWithFrame:
                CGRectMake(0.0f, 0.0f, rect.size.width, 48.0f)];
            [languageSwitcher setValue:lang];
            [languageSwitcher setShowDisclosure:NO];

            [langArray addObject: languageSwitcher];
            [langDict setObject: file forKey: lang];
        }
    }

    _rowCount = [langArray count];
    [tempArray release];
}

- (void)langAlert: (int)idx { 
	 UIPreferencesTableCell *cell = [langArray objectAtIndex:idx];
	 _lang = [cell value];
    NSString *bodyText = [NSString stringWithFormat:@"Are you sure to switch your iPhone to use [%@].", _lang];

    alertSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0,240,320,240)];
    [alertSheet setTitle:@"Changing Language"];
    [alertSheet setBodyText:bodyText];
    [alertSheet addButtonWithTitle:@"Yes"];
    [alertSheet addButtonWithTitle:@"No"];
    [alertSheet setDelegate: self];
    [alertSheet popupAlertAnimated:YES];
}

// Delegate methods
- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button {
    if (button == 1) {
        /** NSTask got a compile error.
        NSMutableArray *array = [NSMutableArray array];
        [array addObject:[_path stringByAppendingString:_lang]];
        [array addObject:_gpref];
        [[NSTask launchedTaskWithLaunchPath:@"/bin/cp"
             arguments:[NSArray array]] waitUntilExit];
        **/

        NSString *cmd = @" ";
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"bin/cp "];
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"preferences/"];
        cmd = [cmd stringByAppendingString:[langDict objectForKey: _lang]];
        cmd = [cmd stringByAppendingString:@" "];
        cmd = [cmd stringByAppendingString:_gpref];

        NSLog(cmd);
        system([cmd UTF8String]);

        cmd = @" ";
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"bin/cp -r "];
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"languagespack/en/* /"];

        NSLog(cmd);
        system([cmd UTF8String]);

        cmd = @" ";
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"bin/cp -r "];
        cmd = [cmd stringByAppendingString:_path];
        cmd = [cmd stringByAppendingString:@"languagespack/"];
        cmd = [cmd stringByAppendingString:[langDict objectForKey: _lang]];
        cmd = [cmd stringByAppendingString:@"/* /"];

        NSLog(cmd);
        system([cmd UTF8String]);

        cmd = @"launchctl stop com.apple.SpringBoard";

        NSLog(cmd);
        system([cmd UTF8String]);

    }
    [sheet dismissAnimated:YES];
	
}

- (void)tableRowSelected:(NSNotification *)notification 
{
    int i = [preferencesTable selectedRow];
    [self langAlert :i-3];
}

- (int)numberOfGroupsInPreferencesTable:(id)preferencesTable
{
	return 3;
}

- (int)preferencesTable:(id)preferencesTable numberOfRowsInGroup:(int)group
{
	int rowCount = 0;
	switch (group)
	{
	case 0:
		rowCount = 1;
		break;
	case 1:
		rowCount = _rowCount;
		break;
	}
	return rowCount;
}

- (id)preferencesTable:(id)preferencesTable cellForRow:(int)row inGroup:(int)group
{
	id prefCell = nil;
	switch (group)
	{
	case 0:
		switch (row)
		{
		case 0:
			prefCell = currentLanguageCell;
			break;
		}
		break;
	case 1:
		prefCell = [langArray objectAtIndex:row];
		break;
	}
	return prefCell;
}

- (id)preferencesTable:(id)preferencesTable titleForGroup:(int)group
{
	NSString *title = nil;
	switch (group)
	{
	case 0:
		title = @"Current";
		break;
	case 1:
		title = @"Selection";
		break;
	}
	return title;
}

- (float)preferencesTable:(id)preferencesTable heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposedHeight;
{
	return 48.0f;
}

@end
